const { ccclass, property } = cc._decorator;

/**
 * 视口内渲染组件参数
 * @param renderNode 渲染节点
 * @param viewPort 视口节点
 * @param firstShowCbk 第一次显示回调
 */
export class InViewCullingProp {
    constructor(
        public renderNode: cc.Node,
        public viewPort: cc.Node,
        public firstShowCbk: Function = null,
    ) { }
}

/**设置节点只在视口范围内渲染，视口外的剔除 */
@ccclass
export class InViewCulling extends cc.Component {
    prop: InViewCullingProp = null

    init(prop: InViewCullingProp) {
        this.prop = prop
    }

    protected onLoad(): void {
        this.prop.renderNode.active = false
    }

    isInViewPort() {
        const aabb = this.prop.renderNode.getBoundingBoxToWorld()
        const viewPortAABB = this.prop.viewPort.getBoundingBoxToWorld()
        const isInView = aabb.intersects(viewPortAABB)
        return isInView
    }

    /**是否显示过 */
    isShown: boolean = false
    update(deltaTime: number) {
        const isInGameView = this.isInViewPort()
        if (this.prop.renderNode.active && !isInGameView) {
            this.prop.renderNode.active = false
        }
        if (!this.prop.renderNode.active && isInGameView) {
            this.prop.renderNode.active = true
            if (!this.isShown) {
                this.isShown = true
                this.prop.firstShowCbk && this.prop.firstShowCbk()
            }
        }

    }
}


